//
//  TGNavMapView.m
//  ConvenientlyTake
//
//  Created by 张奇 on 2023/1/12.
//

#import "TGNavMapView.h"
#import "MANaviRoute.h"
#import "CommonUtility.h"
#import "AMapPrivacyUtility.h"
#import "CustomAnnotationView.h"

#define RouteColor GlobalBlueColor

@interface TGNavMapView ()<MAMapViewDelegate, AMapSearchDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *searchAPI;

//@property (strong, nonatomic) AMapRoute *route;  //路径规划信息
//@property (strong, nonatomic) MANaviRoute * naviRoute;  //用于显示当前路线方案.

@property (nonatomic) CLLocationCoordinate2D *coords;
@property (nonatomic, strong) NSArray *locations;
@property (nonatomic, strong) NSMutableArray *allRoutePolylines;
@property (nonatomic, strong) TGPointAnnotation *endPointAnnotation;

@property (nonatomic, strong) NSMutableArray *pointArray;
@property (nonatomic, assign) NSInteger printCount;

@end

@implementation TGNavMapView

- (instancetype)initWithFrame:(CGRect)frame
//                  coordinates:(CLLocationCoordinate2D *)coords
                    locations:(NSArray *)locations
           endPointAnnotation:(TGPointAnnotation *)endPointAnnotation {
    if (self = [super initWithFrame:frame]) {
        
        self.locations = locations;
        self.endPointAnnotation = endPointAnnotation;
        self.pointArray = [NSMutableArray array];
        for (int i = 0; i < locations.count; i++) {
            CLLocation *location = locations[i];
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
            [self.pointArray addObject:pointAnnotation];
        }
        
//        [AMapPrivacyUtility handlePrivacyAgreeStatus];
        [AMapServices sharedServices].enableHTTPS = YES;
        
        ///初始化地图
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        self.mapView.delegate = self;
        
        ///把地图添加至view
        [self addSubview:_mapView];
    
        [TGGCD executeAfterTime:1 task:^{

            [self createSearch];
        }];
        [_mapView addAnnotation:endPointAnnotation];
        

        //将折线显示在屏幕中心
//        [TGGCD executeAfterTime:0.5 task:^{
//            [self.mapView showAnnotations:@[endPointAnnotation] animated:NO];
//            self.mapView.zoomLevel = self.mapView.zoomLevel-1;
//        }];
        
    }
    return self;
}
#pragma mark - 搜索服务
-(void)createSearch
{
    //配置搜索key
//    [AMapServices sharedServices].apiKey = @"aaaef3b9aa201997f1f6edeb39c4e15f";
    //初始化检索对象
    _searchAPI = [[AMapSearchAPI alloc]init];
    //设置代理
    _searchAPI.delegate = self;

    //路线规划
    for (int i = 0; i < self.locations.count-1; i++) {
        CLLocationCoordinate2D beginCoord = [self.locations[i] coordinate];
        CLLocationCoordinate2D endCoord = [self.locations[i+1] coordinate];
        
        AMapDrivingRouteSearchRequest * drivingTouteRequest2 = [[AMapDrivingRouteSearchRequest alloc]init];
        //设置起点坐标
        drivingTouteRequest2.origin = [AMapGeoPoint locationWithLatitude:beginCoord.latitude longitude:beginCoord.longitude];
        //设置终点坐标
        drivingTouteRequest2.destination = [AMapGeoPoint locationWithLatitude:endCoord.latitude longitude:endCoord.longitude];
        //设置优先级
        drivingTouteRequest2.strategy = 5;
        //设置返回扩展信息
        drivingTouteRequest2.requireExtension = YES;
        
        //发起路径规划请求
        [_searchAPI AMapDrivingRouteSearch:drivingTouteRequest2];
    }
   
}

#pragma mark - 搜索的代理方法


//路径规划的回调函数
-(void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    
    NSLog(@"路线数量%ld", response.route.paths.count);
//    self.currentRouteIndex = 0;
//    self.switchRouteBtn.enabled = self.routeDetailBtn.enabled = self.showTrafficSwitch.enabled = self.totalRouteNums > 0;
//    self.infoLabel.text = @"";
    
    [self presentCurrentRouteCourseWithRoute:response.route];
}

//在地图上显示当前选择的路径
- (void)presentCurrentRouteCourseWithRoute:(AMapRoute *)route {

//    [self.naviRoute removeFromMapView];  //清空地图上已有的路线
    
//    self.infoLabel.text = [NSString stringWithFormat:@"共%u条路线，当前显示第%u条",(unsigned)self.totalRouteNums,(unsigned)self.currentRouteIndex + 1];  //提示信息
    
    MANaviAnnotationType type = MANaviAnnotationTypeDrive; //驾车类型
    
    AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:route.origin.latitude longitude:route.origin.longitude];; //起点
    
    AMapGeoPoint *endPoint = [AMapGeoPoint locationWithLatitude:route.destination.latitude longitude:route.destination.longitude];  //终点
    
    //根据已经规划的路径，起点，终点，规划类型，是否显示实时路况，生成显示方案
    MANaviRoute *naviRoute = [MANaviRoute naviRouteForPath:route.paths[0] withNaviType:type showTraffic:NO startPoint:startPoint endPoint:endPoint];
    
    [naviRoute addToMapView:self.mapView];  //显示到地图上
    
    UIEdgeInsets edgePaddingRect = UIEdgeInsetsMake(20, 20, 20, 20);
    
    //缩放地图使其适应polylines的展示
    [self.allRoutePolylines addObjectsFromArray:naviRoute.routePolylines];
    self.printCount ++;
    if (self.printCount == self.locations.count-1) {
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.allRoutePolylines]
                            edgePadding:edgePaddingRect
                               animated:NO];
        
        [self.mapView showAnnotations:self.pointArray animated:NO];
        self.mapView.zoomLevel = self.mapView.zoomLevel-0.5;
    }
}


#pragma mark - MAMapViewDelegate

//地图上覆盖物的渲染，可以设置路径线路的宽度，颜色等
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    
    //虚线，如需要步行的
    if ([overlay isKindOfClass:[LineDashPolyline class]]) {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth = 6;
//        polylineRenderer.lineDash = YES;
//        polylineRenderer.strokeColor = [UIColor redColor];
        polylineRenderer.strokeColor = RouteColor;
                
        return polylineRenderer;
    }
    
    //showTraffic为NO时，不需要带实时路况，路径为单一颜色，比如驾车线路目前为blueColor
    if ([overlay isKindOfClass:[MANaviPolyline class]]) {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 6;
        
        if (naviPolyline.type == MANaviAnnotationTypeWalking) {
//            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        } else if (naviPolyline.type == MANaviAnnotationTypeRailway) {
//            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        } else {
//            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        polylineRenderer.strokeColor = RouteColor;
        
        return polylineRenderer;
    }
    
    //showTraffic为YES时，需要带实时路况，路径为多颜色渐变
    if ([overlay isKindOfClass:[MAMultiPolyline class]]) {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 6;
//        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.strokeColors = @[RouteColor];
        
        return polylineRenderer;
    }
    
    return nil;
}

//地图上的起始点，终点，拐点的标注，可以自定义图标展示等,只要有标注点需要显示，该回调就会被调用
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[TGPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
//        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
//        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
//        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
//        annotationView.pinColor = MAPinAnnotationColorPurple;
        
        annotationView.canShowCallout = NO;
        annotationView.image = kImage(@"error_single_check_icon");
//        annotationView.centerOffset = CGPointMake(0, 18);
        return annotationView;
    } else {
        
        //标注的view的初始化和复用
        static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        
        if (poiAnnotationView == nil) {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.image = nil;
        
        //拐点的图标标注
        if ([annotation isKindOfClass:[MANaviAnnotation class]]) {
            switch (((MANaviAnnotation*)annotation).type) {
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    poiAnnotationView.image = [UIImage imageNamed:@"car"];
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
        }
        
        return poiAnnotationView;
    }
    return nil;
}

- (NSMutableArray *)allRoutePolylines {
    if (!_allRoutePolylines) {
        _allRoutePolylines = [NSMutableArray array];
    }
    return _allRoutePolylines;
}

@end
